package com.zds.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @className:SpringMVCConfig
 * @date: 2025/6/10 下午5:58
 * @description:
 */
@Configuration
@ComponentScan(value = "com.zds.controller")
@MapperScan("com.zds.mapper")
@EnableWebMvc
public class SpringMVCConfiger implements WebMvcConfigurer {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        //配置DefaultServletHttpRequestHandler，该处理器处理静态资源的访问
        configurer.enable();
    }

    @Bean
    public MappingJackson2HttpMessageConverter  mappingJackson2HttpMessageConverter(){
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //配置ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        //将日期的序列化和反序列化格式设置为 yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"));
        //启用 JSON 输出的缩进功能，使生成的 JSON 字符串更具可读性。
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        //注册 JavaTimeModule，以便正确处理 Java 8 的日期和时间类型（如 LocalDateTime, LocalDate, LocalTime 等）。
        objectMapper.registerModule(new JavaTimeModule());
        converter.setObjectMapper(objectMapper);
        return converter;
    }

    /**
     * 将 MappingJackson2HttpMessageConverter 加入到 Spring MVC 的 HttpMessageConverter 列表中。
     * 这样，Spring MVC 在处理 HTTP 请求和响应时，会使用该转换器进行 JSON 数据的转换。
     * @param converters initially an empty list of converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(mappingJackson2HttpMessageConverter());
    }
    /**
     * 静态资源与请求路径映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/templates/**").addResourceLocations("classpath:/web/jsp/");
    }
}
